package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一次交互由三部分构成：
 * 1.解析请求
 * 2.处理请求
 * 3.响应客户端
 */
public class ClientHander implements Runnable {
    private Socket socket;

    public ClientHander(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {

            //1.解析请求
            HttpRequest request=new HttpRequest(socket);
            HttpResponse response=new HttpResponse(socket);
            /*
            http://localhost:8088/myweb/index.html
            http://localhost:8088/myweb/classTable.html
            http://localhost:8088/TeduStore/index.html
             */

            //2.处理请求
           DispatcherServlet servlet=new DispatcherServlet();
           servlet.service(request,response);
            // 3.发送响应
             /*
                HTTP/1.1 200 OK(CRLF)
                Content-Type: text/html(CRLF)
                Content-Length: 2546(CRLF)(CRLF)
                1011101010101010101......
             */

            response.flush();
            System.out.println("发送响应完毕！");


            /*
            上述内容写好后，打开浏览器输入网址http://localhost:8088/index.html
            测试读取浏览器发送过来的请求内容并在控制台上确定内容
             */
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //一次HTTP交互完毕后要与客户端断开连接（HTTP协议要求）
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }





}
